<?php
require_once ('config.php');
require_once ('databasefunctions.php');
require_once ('displayfunctions.php');
require_once ('businessfunctions.php');
validate_user();
html_header();

switch ($_GET['action']) {
	case "auto" :
		// write off automatically by selecting outstanding transactions within that period
	
		validate_input();

		// clear and create session variable to hold client list to be written off
		if (session_is_registered('ClientList')) {
			unset ($_SESSION['ClientList']);
		}
		else {
			session_register('ClientList');
		}
		
		// obtain list of clients to write off within that period
		$sql = "SELECT * FROM billtransaction WHERE ";
		if ($_GET['CompanyID'] != 'ALL') {
			$sql .= "CompanyID = '" . $_GET['CompanyID'] . "' AND ";
		}
		if (! empty($_GET['CustomerID'])) {
			$sql .= "CustomerID = '" . $_GET['CustomerID'] . "' AND ";
		}
		$sql .= "TransactionDate >= '$DateFrom' AND ";
		$sql .= "TransactionDate <= '$DateTo' AND BillNo IS NULL ORDER BY CompanyID, ClientID ";
		$sql_result = sql_execute($sql);
		
		if (mysql_affected_rows() == 0) {
			message_box($langnotransaction);
			echo "<script>history.go(-1)</script>";
			exit;
		}
		else {
			// create a variable to hold all client transactions
			$last_company = '';
			$last_client = '';
			while ($sql_data = mysql_fetch_array($sql_result)) {
				$amount = $sql_data['Quantity'] * $sql_data['ChargeRate'];
				$client = $sql_data['ClientID'];
				$company = $sql_data['CompanyID'];
				if (($last_client != $client) || ($last_company != $company)) {
					$i = 0;
					$last_client = $client;
					$last_company = $company;
				}
				$_SESSION['ClientList'][$company][$client][$i] = array (
					'TransactionID' => $sql_data['TransactionID'],
					'CompanyID' => $sql_data['CompanyID'],
					'ClientID' => $sql_data['ClientID'],
					'JobID' => $sql_data['JobID'],
					'ChargeID' => $sql_data['ChargeID'],
					'StaffID' => $sql_data['StaffID'],
					'TransactionDate' => $sql_data['TransactionDate'],
					'FromTime' => $sql_data['FromTime'],
					'ToTime' => $sql_data['ToTime'],
					'ChargeRate' => $sql_data['ChargeRate'],
					'Quantity' => $sql_data['Quantity'],
					'Amount' => $amount,
					'Remark' => $sql_data['Remark']
				);
				$i ++;
			}

			create_transaction();

			// get write off date
			$datestamp = getdate();
			$datewriteoff = $datestamp['year'] . "-" . sprintf('%02d',$datestamp['mon']) . 
							"-" . sprintf('%02d',$datestamp['mday']);
			
			echo "<br>$langwriteoffhead<hr>";
			
			// create session variable 'transaction' to hold transaction of a particular company / client
			foreach ($_SESSION['ClientList'] as $client_not_bill) {
				foreach ($client_not_bill as $client) {
					// get bill number
					$_SESSION['transaction'] = $client ;
					print_result('writeoff',$datewriteoff);
					echo "<hr>";
				}
			}
		}
		
		break;
		
	case "manual" :
	// display list of un-bill transaction for selection
		$DateFrom = '';
		$DateTo = '';
		validate_input();
		create_transaction();
		select_form('writeoff');
		break;
		
	case "recover_select" :
		// display list of transactions written off for selection
		$DateFrom = '';
		$DateTo = '';
		validate_input();
		create_transaction();
		select_form('recover');
		break;
	
	case "print" :
		// obtain all HTTP 'GET' keys
		$var_from_http_get = array_keys($_GET);
		
		// extract all keys which starts with 'item' and store them into $unbill
		foreach ($var_from_http_get as $item) {
			if (substr($item,0,4) == 'item') {
				$line_no = substr($item, 4);
				$unbill[] = $line_no;
			}
		}
			
		// modify user selected transactions for write off
		if (! $unbill) {
			message_box($langnotransaction);
			echo "<script>history.go(-1)</script>";
			exit;
		}
		
		// move record pointer in $_SESSION['transaction'] to the 1st record
		reset ($_SESSION['transaction']);
		$temp = current($_SESSION['transaction']);
			
		if ($_GET['subaction'] != 'recover') {
			// validate write off date
			if (! empty($_GET['writeoffdate'])) {
				$datewriteoff = validate_date($_GET['writeoffdate'], 1);
			}
			else {
				$datestamp = getdate();
				$datewriteoff = $datestamp['year'] . "-" . sprintf('%02d',$datestamp['mon']) . 
								"-" . sprintf('%02d',$datestamp['mday']);
			}
			if (! $datewriteoff) {
				$error_text .= "<br>- $langinvaliddate<br>";
			}
			
			// display error and return if any
			if ($error_text) {
				message_box($error_text);
				?>
				<script>history.go(-1)</script>
				<?
				exit;
			}
		}
		
		// display title bar
		title_bar($langwriteoff);
		
		// erase array values in session variable 'transaction' which are not in $unbill variable
		// i.e. erase transactions not selected for write offf/recover
		foreach ($_SESSION['transaction'] as $index => $content) {
			$record_found = 0;
			foreach ($unbill as $value) {
				if ($value == $index) {
					$record_found = 1;
					break;
				}
			}
			if ($record_found == 0) {
				unset ($_SESSION['transaction'][$index]);
			}
		}
		
		// call printing function
		if ($_GET['subaction'] != 'recover') print_result('writeoff', $datewriteoff);
		else print_result('recover');
		
		exit;
		break;
		
	default :
	// display client / date / company selection form
		title_bar($langwriteoff, 0,0);
		?>
		<form name='selectform'>
		<table>
			<tr>
				<td bgcolor='<? echo $color1 ?>'><? echo $langcompanyid?>
				<td><select name='CompanyID'>
						<option value = 'ALL' selected>
					<?
						$company_list = get_company_list();
						foreach ($company_list as $company) {
							echo "<option value='" . $company['CompanyID'] . "'>";
							echo $company['CompanyID'] . " - " . $company['CompanyName'];
						}
					?>	
					</select>		
			<tr>
				<td bgcolor='<? echo $color1 ?>'><? echo $langclientid ?>
				<td><input type = 'text' name = 'ClientID'>
					<input type = 'button' value = 'S' onclick=opensearch('client','selectform.ClientID')>
			<tr>
				<td bgcolor='<? echo $color1 ?>'><? echo $langwriteoffmethod ?>
				<td><select name = 'writeoffmethod'>
						<option value = 'auto'><? echo $langautowriteoff ?>
						<option value = 'manual'><? echo $langmanualwriteoff ?>
						<option value = 'recover_select'><? echo $langrecover ?>
					</select>
			<tr>
				<td bgcolor='<? echo $color1 ?>'><? echo $langdatefrom ?>
				<td><input type = 'text' name = 'FromDate'>
			<tr>
				<td bgcolor='<? echo $color1 ?>'><? echo $langdateto ?>
				<td><input type = 'text' name = 'ToDate'>
		</table>
		<input type = 'button' value = '<? echo $langexecute ?>' onclick='goaction()'>
		</form>
		<script>
		function opensearch(search_type, fieldname) {
				url_text = 'search.php?master=' + search_type + '&inputname=' + fieldname;
				window.open(url_text ,'','width=700,height=500');
		}
				
		function goaction() {
			// create difference href string based on user action
			hrefstring = 'writeoff.php?ClientID=';
			hrefstring = hrefstring + document.selectform.ClientID.value;
			hrefstring = hrefstring + '&FromDate=' + document.selectform.FromDate.value;
			hrefstring = hrefstring + '&ToDate=' + document.selectform.ToDate.value;
			hrefstring = hrefstring + '&action=';
			
			action = document.selectform.writeoffmethod.selectedIndex;		
			actionvalue = document.selectform.writeoffmethod.options[action].value;
			
			company = document.selectform.CompanyID.selectedIndex;
			companyid = document.selectform.CompanyID.options[company].value;
			
			this.location = hrefstring + actionvalue + '&CompanyID=' + companyid;
		}
		</script>
		<?
		break;
}

html_footer();


function validate_input() {
// validate user input for write off range
	global $DateFrom, $DateTo, $langinvalidclient, $langinvaliddate, $langfrom, $langto, $langinvaliddaterange;
	
	// if client ID is empty and action is auto, no need to check client ID
	if (! (empty($_GET['ClientID']) && $_GET['action'] == 'auto')) {
		if (! validate_client($_GET['ClientID'])) {
			$error_text .= "<br>- $langinvalidclient<br>";
		}
	}
	
	$DateFrom = validate_date($_GET['FromDate'], 1);
	if (! $DateFrom) {
		$error_text .= "<br>- $langinvaliddate $langfrom<br>";
	}
	
	$DateTo = validate_date($_GET['ToDate'], 1);
	if (! $DateTo) {
		$error_text .= "<br>- $langinvaliddate $langto<br>";
	}
	
	if ($DateFrom && $DateTo & ($DateFrom > $DateTo)) {
		$error_text .= "<br>- $langinvaliddaterange<br>";	
	}
	
	if ($error_text) {
		message_box($error_text);
		?>
		<script>history.go(-1)</script>
		<?
		exit;	
	}	
}

function print_result ($action, $write_off_date=0) {
// displaying the transactions to write off in html
	global $langwriteoffhead, $langrecoverhead, $langclientid, $langclientname, $langwriteoffdate,
		   $langjobid, $langchargeid, $langstaffid, $langtransactiondate, $langtimefrom, $langtimeto,
		   $langprice, $langqtyhour, $langamount, $langtotal, $langreference;
	
	if ($action == 'writeoff') {
		// convert write off date format from YYYYMMDD to user profile format
		$user_date = convert_mysql_date($write_off_date);
		$user_date = substr($user_date,0,2) . "/" . substr($user_date,2,2) . "/" . substr($user_date,4,4);
	}

	reset ($_SESSION['transaction']);
	$temp = current($_SESSION['transaction']);
	
	// get company name
	$sql = "SELECT CompanyName FROM companymaster WHERE CompanyID = '" ;
	$sql .= $temp['CompanyID'] . "'";
	$sql_result = sql_execute($sql);
	$sql_data = mysql_fetch_array($sql_result);
	$companyname = $sql_data['CompanyName'];
	
	// get client name
	$sql = "SELECT * FROM clientmaster WHERE ClientID = '" ;
	$sql .= $temp['ClientID'] . "'";
	$sql_result = sql_execute($sql);
	$sql_data = mysql_fetch_array($sql_result);
	
	echo "<h3 align='center'>$companyname</h3><h5>";
	if ($action == 'writeoff') echo $langwriteoffhead;
	else echo $langrecoverhead;
	echo "</h5>
		<table>
		  <tr><td bgcolor='$color1'>$langclientid<td>" . $temp['ClientID'];
	echo "<tr><td bgcolor='$color1'>$langclientname<td>" . $sql_data['ClientName'] ;
	if ($action == 'writeoff') 
		echo "<tr><td bgcolor='$color1'>$langwriteoffdate" . "<td>" . $user_date ;
	echo "</table>
		<br>
		<table>
		<tr bgcolor='$color1' align='center'>
			<td>$langjobid
			<td>$langchargeid
			<td>$langstaffid
			<td>$langtransactiondate
			<td>$langtimefrom
			<td>$langtimeto
			<td>$langprice
			<td>$langqtyhour
			<td>$langamount";
		
	// list un-bill transaction
	$total_amount = 0;
	foreach ($_SESSION['transaction'] as $content) {
		$user_date = convert_mysql_date($content['TransactionDate']);
		$user_date = substr($user_date,0,2) . "/" . substr($user_date,2,2) . "/" . substr($user_date,4,4);
		echo "\n<tr>";
		echo "<td>" . $content['JobID'];
		echo "<td>" . $content['ChargeID'];
		echo "<td>" . $content['StaffID'];
		echo "<td align='right'>" . $user_date;
		echo "<td align='right'>" . substr($content['FromTime'],0,5);
		echo "<td align='right'>" . substr($content['ToTime'],0,5);
		echo "<td align='right'>" . $content['ChargeRate'];
		echo "<td align='right'>" . $content['Quantity'];
		echo "<td align='right'>";
		printf('%.2f', $content['Amount']) ;
		$total_amount += $content['Amount'];
		
		if (! empty($content['Remark'])) {
			echo "\n<tr><td><td align='right'>$langreference :<td colspan='6'>" . $content['Remark'];	
		}
		echo "\n<tr><td colspan='9'>";
		
		if ($action == 'writeoff') {
			// update write off date / number to bill transaction
			$sql = "UPDATE billtransaction SET BillDate = '$write_off_date', BillNo = 'WRITE OFF', ";
		}
		else {
			// replace bill date / number with null value in bill transaction
			$sql = "UPDATE billtransaction SET BillDate = NULL, BillNo = NULL, ";
		}
		$sql .= "UpdateUser = '" . $_SESSION['UserID'] . "', ";
		$sql .= "UpdateProgram = '" . $_SERVER['PHP_SELF'] . "' ";		
		$sql .= " WHERE TransactionID = " . $content['TransactionID'];
		sql_execute($sql);
	}
	echo "\n";
	echo "<tr>
		<td align = 'right' colspan = '8'>$langtotal
		<td align = 'right'>";
		printf('%.2f', $total_amount);
	echo "</table>";
}

function create_transaction() {
	// create temp session variable
	if (session_is_registered('transaction')) {
		unset ($_SESSION['transaction']);
	}
	else {
		session_register('transaction');
	}
}

function select_form($action) {
// display un-billed items
	global $langcompanyid, $langclientid, $langjobid, $langchargeid, $langstaffid, $langtransactiondate,
		   $langtimefrom, $langtimeto, $langprice, $langqtyhour, $langamount, $langmarkitem,
		   $langwrteoffdate, $langemptytoday, $langwriteoff, $langrecover, $DateFrom, $DateTo,
		   $langnotransaction, $langwriteoffdate ;

	$sql = "SELECT * FROM billtransaction WHERE ";
	$sql .= "ClientID = '" . $_GET['ClientID'] . "' AND ";
	$sql .= "CompanyID = '" . $_GET['CompanyID'] . "' AND ";
	$sql .= "TransactionDate >= '$DateFrom' AND ";
	$sql .= "TransactionDate <= '$DateTo' AND ";
	if ($action == 'recover') $sql .= "BillNo = 'WRITE OFF'";
	else $sql .= "BillNo IS NULL";

	$sql_result = sql_execute($sql);
	
	if (mysql_affected_rows() == 0) {
		message_box($langnotransaction);
		echo "<script>history.go(-1)</script>";
		exit;
	}
	else {
		// display form title
		title_bar($langwriteoff);
		echo "<br><br>$langmarkitem<br><br>
			<form method='GET' action='writeoff.php'>";
		if ($action == 'writeoff') {
			echo "<table>
					<tr>
						<td>$langwriteoffdate
						<td><input type = 'text' name = 'writeoffdate'>$langemptytoday
					</table>";
					
		}
		echo "<table>
			<tr bgcolor='$color1'>
				<td>
				<td>$langcompanyid
				<td>$langclientid
				<td>$langjobid
				<td>$langchargeid
				<td>$langstaffid
				<td>$langtransactiondate
				<td>$langtimefrom
				<td>$langtimeto
				<td>$langprice
				<td>$langqtyhour
				<td>$langamount";

		// list un-bill transaction
		$i = 0;
		while ($sql_data = mysql_fetch_array($sql_result)) {
			$amount = $sql_data['Quantity'] * $sql_data['ChargeRate'];
			$user_date = convert_mysql_date($sql_data['TransactionDate']);
			$user_date = substr($user_date,0,2) . "/" . substr($user_date,2,2) . "/" . substr($user_date,4,4);
			echo "\n<tr>";
			echo "<td><input type = 'checkbox' name = 'item$i'>";
			echo "<td>" . $sql_data['CompanyID'];
			echo "<td>" . $sql_data['ClientID'];
			echo "<td>" . $sql_data['JobID'];
			echo "<td>" . $sql_data['ChargeID'];
			echo "<td>" . $sql_data['StaffID'];
			echo "<td>" . $user_date;
			echo "<td>" . $sql_data['FromTime'];
			echo "<td>" . $sql_data['ToTime'];
			echo "<td>" . $sql_data['ChargeRate'];
			echo "<td>" . $sql_data['Quantity'];
			echo "<td>" . $amount ;
			
			$_SESSION['transaction'][$i] = array (
				'TransactionID' => $sql_data['TransactionID'],
				'CompanyID' => $sql_data['CompanyID'],
				'ClientID' => $sql_data['ClientID'],
				'JobID' => $sql_data['JobID'],
				'ChargeID' => $sql_data['ChargeID'],
				'StaffID' => $sql_data['StaffID'],
				'TransactionDate' => $sql_data['TransactionDate'],
				'FromTime' => $sql_data['FromTime'],
				'ToTime' => $sql_data['ToTime'],
				'ChargeRate' => $sql_data['ChargeRate'],
				'Quantity' => $sql_data['Quantity'],
				'Amount' => $amount,
				'Remark' => $sql_data['Remark']
			);
			$i ++;
		}
	}
	echo "</table>";
	echo "\n<input type = 'hidden' name = 'action' value = 'print'>";
	if ($action == 'writeoff') {
		echo "\n<input type = 'hidden' name = 'subaction' value = 'writeoff'>";
		echo "\n<input type = 'submit' value = '$langwriteoff'>";
	}
	else {
		echo "\n<input type = 'hidden' name = 'subaction' value = 'recover'>";
		echo "\n<input type = 'submit' value = '$langrecover'>";
	}			
	echo "</form>";
}

?>